package com.example.backend.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.backend.domain.entity.RestBean;
import com.example.backend.domain.po.Employees;
import com.example.backend.service.IEmployeesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dyy
 * @since 2025-05-27
 */
@RestController
@RequestMapping("/api/employees")
public class EmployeesController {
    @Autowired
    private IEmployeesService employeesService;

    // 新增员工
    @PostMapping
    public RestBean<Void> addEmployee(@RequestBody Employees employee) {
        boolean save = employeesService.save(employee);
        return save==true?RestBean.success():RestBean.failure(400,"添加失败");
    }

    // 分页查询
    @GetMapping("/page")
    public RestBean<IPage<Employees>> getByPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        IPage<Employees> page = new Page<>(pageNum, pageSize);
        return RestBean.success(employeesService.page(page));
    }

    // 条件查询
    @GetMapping("/search")
    public RestBean<List<Employees>> searchEmployees(
            @RequestParam(required = false) String fullName,
            @RequestParam(required = false) String position) {
        LambdaQueryWrapper<Employees> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(fullName), Employees::getFullName, fullName)
                .like(StringUtils.hasText(position), Employees::getPosition, position);
        return RestBean.success(employeesService.list(wrapper));
    }

    // 更新员工信息
    @PutMapping("/{id}")
    public RestBean<Void> updateEmployee(
            @PathVariable Integer id,
            @RequestBody Employees employee) {
        employee.setId(id);
        employeesService.updateById(employee);
        return RestBean.success();
    }

    // 删除员工
    @DeleteMapping("/{id}")
    public RestBean<Void> deleteEmployee(@PathVariable Integer id) {
        employeesService.removeById(id);
        return RestBean.success();
    }

    //根据id查询员工
    @GetMapping("/{id}")
    public RestBean<Employees> getByIdEmployee(@PathVariable Integer id){
        Employees employees = employeesService.getById(id);
        return RestBean.success(employees);
    }
}
